package com.lytis.zoovideo.controller;

import com.lytis.zoovideo.common.R;
import com.lytis.zoovideo.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author :DongPeiLei
 * @description :
 * @create :2022-05-28 10:45:00
 */
@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {
    /**
     * 1.文件保存在服务器，url地址保存在数据库
     * 上传成功之后返回成功保存的url地址
     */
    @Autowired
    VideoService videoService;

    @PostMapping
    public R upload(@RequestParam MultipartFile file, HttpServletRequest request) {
        if (!file.isEmpty()) {
            String OriginalFilename = file.getOriginalFilename();//获取原文件名
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名
            String uploadPath = "F:\\大三\\项目实践课\\zooLivingDesign\\zooVideo\\src\\main\\resources\\static\\" + suffixName.substring(1);
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            //重新随机生成名字
            String filename = UUID.randomUUID().toString() + suffixName;
            File localFile = new File(uploadPath + "\\" + filename);
            try {
                file.transferTo(localFile); //把上传的文件保存至本地
                /**
                 * 这里应该把filename保存到数据库,供前端访问时使用
                 */
                return R.ok().data("filePath", filename);//上传成功，返回保存的文件地址
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("上传失败");
                return R.error().message("上传失败");
            }
        } else {
            System.out.println("文件为空");
            return R.error().message("文件为空");
        }
    }
}
